package com.jinhua.huaoj.judge.codesandbox.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.jinhua.huaoj.common.ErrorCode;
import com.jinhua.huaoj.exception.BusinessException;
import com.jinhua.huaoj.judge.codesandbox.CodeSandBox;
import com.jinhua.huaoj.judge.model.ExecuteCodeRequest;
import com.jinhua.huaoj.judge.model.ExecuteCodeResponse;

/**
 * 远程代码沙箱（调用远程代码沙箱）
 */
public class RemoteCodeSandBox implements CodeSandBox {

    //    定义鉴权请求头
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secrety";


    @Override
    public ExecuteCodeResponse excuteCode(ExecuteCodeRequest executeCodeRequest) {
        System.out.println("远程代码沙箱");
        String url = "http://192.168.121.128:9001/executeCode";
        String executeCodeRequestJSON = JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER, AUTH_REQUEST_SECRET)
                .body(executeCodeRequestJSON)
                .execute()
                .body();
        if (StrUtil.isBlank(responseStr)){
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR);
        }
        return JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);

    }
}
